package com.itheima.sh.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "queryByIdback")
    public Map queryById(@PathVariable("id") String id){

        // 1 URL
        //String url = "http://localhost:8081/user/" + id;


        // 从Eureka中获取服务的实例（IP、PORT）
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance serviceInstance = instances.get(0);  // 服务实例对象
//
//        String url = "http://"+serviceInstance.getHost()+":"+serviceInstance.getPort()+"/user/" + id;

        // Ribbon 实现 Ribbon
        String url = "http://user-service/user/" + id;

        // 2 发送请求
        Map map = restTemplate.getForObject(url, Map.class);
        // 3 得到结果
        System.out.println(map);
        return map;
    }

    public Map queryByIdback(@PathVariable("id") String id) {
        return new HashMap();
    }
}
